package cn.icatw.gulimall.cart.interceptor;

import cn.icatw.common.constant.AuthServerConstant;
import cn.icatw.common.constant.CartConstant;
import cn.icatw.common.vo.MemberRespVo;
import cn.icatw.gulimall.cart.vo.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 购物车拦截器
 *
 * @author icatw
 * @date 2022/3/23
 * @email 762188827@qq.com
 * @apiNote 在执行目标方法之前，判断用户的登陆状态，并封装传递给controller
 */
@Slf4j
public class CartInterceptor implements HandlerInterceptor {
    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    /**
     * 前处理
     * 临时用户信息存在cookie中
     * 登陆用户信息存在session中
     *
     * @param request  请求
     * @param response 响应
     * @param handler  处理程序
     * @return boolean
     * @throws Exception 异常
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoTo userInfoTo = new UserInfoTo();
        HttpSession session = request.getSession();
        MemberRespVo member = (MemberRespVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (member != null) {
            //用户登陆
            userInfoTo.setUserId(member.getId());
        }
        //用户未登陆
        //TODO cookie获取不到
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                //user-key
                String name = cookie.getName();
                if (name.equals(CartConstant.TEMP_USER_COOKIE_NAME)) {
                    userInfoTo.setUserKey(cookie.getValue());
                    userInfoTo.setTempUser(true);
                }
            }
        }
        if (StringUtils.isEmpty(userInfoTo.getUserKey())) {
            //    假如第一个添加购物车，没有临时用户，则自定义一个user-key
            //没有临时用户则新建一个临时用户
            String s = UUID.randomUUID().toString();
            log.info("临时用户key："+s);
            userInfoTo.setUserKey(s);
        }
        //目标方法执行之前
        threadLocal.set(userInfoTo);
        return true;
    }

    /**
     * 处理后
     * 业务执行之后，将user-key存放到session中
     * 如果没有临时用户一定要保存一个临时用户
     *
     * @param request      请求
     * @param response     响应
     * @param handler      处理程序
     * @param modelAndView 模型和视图
     * @throws Exception 异常
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //从本地线程池里获取userInfoTo
        UserInfoTo userInfoTo = threadLocal.get();
        //TODO 考虑remove线程池，防止内存溢出
        //假如不判断当前cookie是否携带user-key，则持续的延长临时用户过期时间（重复设置MaxAge）
        if (!userInfoTo.isTempUser()) {
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            //Domain作用域
            cookie.setDomain("gulimall.com");
            //TODO 设置path
            cookie.setPath("/");
            //MaxAge最大存活时间，过期时间，一个月
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
